package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"git.tmuyu.com.cn/beego/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

//subUrl 是类似于 /user_view /wx_user_edit 这样的 具体可以到router查阅
//思路是 先通过OAuth2来获取code 然后再根据code获取 openid 最后重定向至本页
func GetWxId(c *context.Context, subUrl string) (sn *models.WxUserInfo, err error) {
	var wxbase models.WxBase
	wxbase.AppSecret = beego.AppConfig.String("appSecret")
	wxbase.AppID = beego.AppConfig.String("appID")
	if code := c.Input.Query("code"); code == "" {
		encodUrl := url.QueryEscape("http://" + beego.AppConfig.String("baseURL") + "/" + subUrl)
		urlStr := "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
			wxbase.AppID + "&redirect_uri=" + encodUrl +
			"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
		c.Redirect(302, urlStr)
		return nil, nil
	} else {
		if sn, err = getWxOpendidFromoauth2(code, wxbase.AppID, wxbase.AppSecret); err == nil {
			return
		} else {
			return
		}
	}

	return
}

func getWxOpendidFromoauth2(code, appid, secret string) (*models.WxUserInfo, error) {

	requestLine := strings.Join([]string{"https://api.weixin.qq.com/sns/oauth2/access_token",
		"?appid=", appid,
		"&secret=", secret,
		"&code=", code,
		"&grant_type=authorization_code"}, "")
	resp, err := http.Get(requestLine)

	if err != nil || resp.StatusCode != http.StatusOK {
		fmt.Println("发送get请求获取 openid 错误", err)
		logs.Error("发送get请求获取 openid 错误", err)
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error("发送get请求获取 openid 读取返回body错误", err)
		return nil, err
	}
	if bytes.Contains(body, []byte("errcode")) {

		ater := models.AccessTokenErrorResponse{}
		err = json.Unmarshal(body, &ater)

		if err != nil {
			logs.Error("发送get请求获取 openid 的错误信息 %+v\n", ater)
			return nil, err
		}
		return nil, fmt.Errorf("%s", ater.Errmsg)

	} else {
		atr := models.WxUserInfo{}
		err = json.Unmarshal(body, &atr)
		if err != nil {
			logs.Error("发送get请求获取 openid 返回数据json解析错误", err)
			return nil, err
		}
		return &atr, nil
	}
}
